import styles from "@styles/updateChannel.module.less";
import classNames from "classnames";
import GeekIcon from "@shared/geekIcon";
import React, { useEffect, useState } from "react";
import {
  useDeleteUserChannelMutation,
  useRequestUserChannelsQuery,
} from "@service/channelEndpoints";
import { useNavigate, useParams } from "react-router-dom";
import { SlideRef } from "@shared/slide";
import EditButton from "@pages/home/common/EditButton";

interface Props {
  slideRef: React.RefObject<SlideRef | null>;
}

export default function Selected({ slideRef }: Props) {
  const { selectedChannels } = useRequestUserChannelsQuery(undefined, {
    selectFromResult: (response) => ({
      ...response,
      selectedChannels: response.data?.data.channels || [],
    }),
  });

  const [deleteUserChannel] = useDeleteUserChannelMutation();
  const { cid } = useParams();
  const navigate = useNavigate();

  const [editing, setEditing] = useState(false);

  useEffect(() => {
    if (selectedChannels.length === 4) {
      setEditing(false);
    }
  }, [selectedChannels.length]);
  return (
    <>
      <div className={styles.title}>
        <h3>我的频道</h3>
        <h4>点击进入频道</h4>
        {/* 如果正处于编辑编辑状态, 显示完成, 否则显示编辑 */}
        <EditButton
          render={selectedChannels.length > 4}
          value={editing}
          onChange={setEditing}
        />
      </div>
      <div className={styles.list}>
        {selectedChannels.map((channel) => (
          <span
            key={channel.id}
            className={classNames({
              [styles.active]: Number(cid) === Number(channel.id),
            })}
            onClick={() => {
              navigate(`/${channel.id}`);
              slideRef.current?.close();
            }}
          >
            {channel.name}
            {editing && Number(channel.id) !== 0 && (
              <GeekIcon
                type={"iconbtn_tag_close"}
                onClick={(event) => {
                  // 阻止事件冒泡
                  event.stopPropagation();
                  deleteUserChannel(channel.id)
                    .unwrap()
                    .then(() => {
                      // 如果删除的频道正好是当前选中的频道
                      if (Number(channel.id) === Number(cid)) {
                        navigate(`/0`);
                      }
                    });
                }}
              />
            )}
          </span>
        ))}
        {/*<span className={styles.active}>
          人工智能 <GeekIcon type={"iconbtn_tag_close"} />
        </span>*/}
      </div>
    </>
  );
}
